let zTree;
let setting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/examget/getexamSortTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    callback: {
        onClick: zTreeOnClick
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    }
};
let setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/examget/getexamSortTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            let zTree = $.fn.zTree.getZTreeObj("menuTree"), nodes = zTree.getSelectedNodes();
            let v = "";
            let vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (let i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            let idem = $("#sortId");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};

function zTreeOnClick(event, treeId, treeNode) {
    $("#createQuestions").hide();
    $("#questionlist").show();
    $("#myTable").bootstrapTable('destroy');
    if (treeNode.sortId == "0") {
        query("");
    } else {
        query(treeNode.sortId);
    }
}

$(function () {
    $(".js-cbut").unbind("click").click(function () {
        $("#questionlist").hide();
        $("#createQuestions").show();
        document.getElementById("from").reset();
        $("#sortId").attr("data-value");
        $(".js-optselect").remove();
        $(".js-save").unbind("click").click(function () {
            insertExamQuestions();
        })
    })
    $(".js-child-item").unbind("click").click(function () {
        addChildItem();
    })
    $("#examType").bind("change").change(function () {
        if ($(this).val() == "2") {
            $("#content").hide();
        } else {
            $("#content").show();
        }
    })
    $.ajax({
        url: "/ret/examget/getexamSortTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            zTree = $.fn.zTree.init($("#tree"), setting, data);// 初始化树节点时，添加同步获取的数据
            $.fn.zTree.init($("#menuTree"), setting1, data);
        }
    });

    $("#sortId").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });
    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });
    query("");
})

function query(sortId) {
    $("#myTable").bootstrapTable({
        url: '/ret/examget/getExamQuestionsListBySortId?sortId=' + sortId,
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'recordId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        },
            {
                field: 'num',
                title: '序号',//标题  可不加
                width: '50px',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {
                field: 'title',
                title: '试题标题',
                sortable: true,
                width: '200px'
            },
            {
                field: 'sortName',
                width: '50px',
                title: '试题分类'
            },
            {
                field: 'examType',
                title: '试题类型',
                width: '50px',
                formatter: function (value, row, index) {
                    if (value == "0") {
                        return "单选";
                    } else if (value == "1") {
                        return "多选";
                    } else if (value == "2") {
                        return "简述";
                    }

                }
            },
            {
                field: 'grade',
                width: '50px',
                title: '分值'
            },
            {
                field: 'answer',
                width: '200px',
                title: '答案'
            },
            {
                field: 'opt',
                width: '150px',
                align: 'center',
                title: '操作',
                formatter: function (value, row, index) {
                    return createOptBtn(row.recordId);
                }
            }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    let temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order
    };
    return temp;
};

function createOptBtn(recordId) {
    let html = "<a href=\"javascript:void(0);details('" + recordId + "')\" class=\"btn btn-sky btn-xs\" >详情</a>&nbsp;&nbsp;" +
        "<a href=\"javascript:void(0);edit('" + recordId + "')\" class=\"btn btn-success btn-xs\" >编辑</a>&nbsp;&nbsp;";
    html += "<a href=\"javascript:void(0);del('" + recordId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    return html;
}

function del(recordId) {
    if (confirm("确定删除当前试题吗？")) {
        $.ajax({
            url: "/set/examset/deleteExamQuestions",
            type: "post",
            dataType: "json",
            data: {
                recordId: recordId
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    }
}

function details(recordId) {
    window.open("/app/core/exam/questionsdetails?recordId=" + recordId);
}

function edit(recordId) {
    $("#questionlist").hide();
    $("#createQuestions").show();
    document.getElementById("from").reset();
    $("#sortId").attr("data-value");
    $(".js-optselect").remove();
    $.ajax({
        url: "/ret/examget/getExamQuestionsById",
        type: "post",
        dataType: "json",
        data: {recordId: recordId},
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                for (let id in data.list) {
                    if (id == "sortId") {
                        $("#" + id).attr("data-value", data.list[id]);
                        $.ajax({
                            url: "/ret/examget/getExamSortById",
                            type: "post",
                            dataType: "json",
                            async: false,
                            data: {
                                sortId: data.list[id]
                            },
                            success: function (res) {
                                if (res.status == "200") {
                                    $("#" + id).val(res.list.sortName);
                                } else if (res.status == "100") {
                                    layer.msg(sysmsg[res.msg]);
                                } else {
                                    console.log(res.msg);
                                }
                            }
                        });
                    } else {
                        if (id != 'content') {
                            $("#" + id).val(data.list[id]);
                        } else {
                            if (id != 'examType') {
                                $("#" + id).val(data.list[id]);
                                if (data.list[id] != "2") {
                                    $("#content").show();
                                    let childItemArr = JSON.parse(data.list[id]);
                                    createChildItem(childItemArr);
                                } else {
                                    $("#content").hide();
                                }
                            }
                        }
                    }
                }
                $(".js-save").unbind("click").click(function () {
                    updateExamQuestions(recordId);
                })
            }
        }
    })
}

function deleteChildItem(Obj) {
    $(Obj).parent("td").parent("tr").remove();
}

function getParam() {
    let paramArr = [];
    $("#child-item-table").find("tr").next().each(function () {
        let json = {};
        let optValue = $(this).children("td").eq(0).find("input").val();
        let childTitle = $(this).children("td").eq(1).find("input").val();
        json.optValue = optValue;
        json.childTitle = childTitle;
        paramArr.push(json);
    });
    return JSON.stringify(paramArr);
}

function insertExamQuestions() {
    $.ajax({
        url: "/set/examset/insertExamQuestions",
        type: "post",
        dataType: "json",
        data: {
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            sortId: $("#sortId").attr("data-value"),
            examType: $("#examType").val(),
            content: getParam(),
            answer: $("#answer").val(),
            grade: $("#grade").val(),
            remark: $("#remark").val()
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            }
        }
    })
}

function updateExamQuestions(recordId) {
    $.ajax({
        url: "/set/examset/updateExamQuestions",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId,
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            sortId: $("#sortId").attr("data-value"),
            examType: $("#examType").val(),
            content: getParam(),
            answer: $("#answer").val(),
            grade: $("#grade").val(),
            remark: $("#remark").val()
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#myTable").bootstrapTable("refresh");
            }
        }
    })
}

function addChildItem() {
    $("#child-item-table").append("<tr class='js-optselect'><td><input type='text' name='optValue' class='form-control'></td><td><input type='text' name='childTitle' class='form-control'></td>" +
        "<td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a></td></tr>");
}

function createChildItem(childItemArr) {
    $("#child-item-table").find("tr").next().remove();
    for (let i = 0; i < childItemArr.length; i++) {
        $("#child-item-table").append("<tr class='js-optselect'><td><input type='text' name='optValue' value='" + childItemArr[i].optValue + "' class='form-control'></td>" +
            "<td><input type='text' name='childTitle' class='form-control' value='" + childItemArr[i].childTitle + "'></td>" +
            "<td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a></td></tr>");

    }
}
